import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Card, Table, Button, Input, Select, Space, Tag, message, Modal, Form, Switch, InputNumber } from 'antd'
import { PlusOutlined, SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { 
  fetchCategoryTree,
  fetchCategoryList,
  addCategory,
  editCategory,
  removeCategory,
  changeCategoryStatus,
  fetchParentCategories,
  resetCurrentCategory
} from '@/store/slices/categorySlice'
import './index.scss'

const CategoryManagement = () => {
  const dispatch = useDispatch()
  const { 
    categoryList, 
    categoryTree,
    parentCategories,
    total, 
    currentPage, 
    pageSize, 
    loading 
  } = useSelector((state) => state.category)
  
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [modalType, setModalType] = useState('add') // 'add' or 'edit'
  const [currentRecord, setCurrentRecord] = useState(null)
  const [form] = Form.useForm()
  
  // 搜索表单状态
  const [searchForm, setSearchForm] = useState({
    name: '',
    isEnabled: null
  })

  // 初始化加载数据
  useEffect(() => {
    loadCategoryList()
    dispatch(fetchCategoryTree())
    dispatch(fetchParentCategories())
  }, [])

  // 加载分类列表
  const loadCategoryList = (params = {}) => {
    dispatch(fetchCategoryList({
      page: params.page || currentPage,
      size: params.size || pageSize,
      ...searchForm,
      ...params
    }))
  }

  // 搜索
  const handleSearch = () => {
    loadCategoryList({ page: 1 })
  }

  // 重置
  const handleReset = () => {
    setSearchForm({
      name: '',
      isEnabled: null
    })
    dispatch(fetchCategoryList({ page: 1, size: pageSize }))
  }

  // 打开新增对话框
  const handleCreate = () => {
    setModalType('add')
    setCurrentRecord(null)
    form.resetFields()
    form.setFieldsValue({
      parentId: 0,
      level: 1,
      sort: 0,
      isEnabled: 1
    })
    setIsModalVisible(true)
  }

  // 打开编辑对话框
  const handleEdit = (record) => {
    setModalType('edit')
    setCurrentRecord(record)
    form.setFieldsValue({
      name: record.name,
      parentId: record.parentId,
      level: record.level,
      sort: record.sort,
      isEnabled: record.isEnabled,
      url: record.url
    })
    setIsModalVisible(true)
  }

  // 删除
  const handleDelete = (id, name) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除分类"${name}"吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const result = await dispatch(removeCategory(id))
        if (result.type.includes('fulfilled')) {
          message.success('删除成功')
          loadCategoryList()
          dispatch(fetchCategoryTree()) // 刷新分类树
        } else {
          message.error(result.payload || '删除失败')
        }
      }
    })
  }

  // 切换状态
  const handleStatusChange = async (id, checked) => {
    const isEnabled = checked ? 1 : 0
    const result = await dispatch(changeCategoryStatus({ id, isEnabled }))
    if (result.type.includes('fulfilled')) {
      message.success('状态更新成功')
      loadCategoryList()
    } else {
      message.error(result.payload || '状态更新失败')
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      
      if (modalType === 'add') {
        const result = await dispatch(addCategory(values))
        if (result.type.includes('fulfilled')) {
          message.success('新增成功')
          setIsModalVisible(false)
          loadCategoryList()
          dispatch(fetchCategoryTree()) // 刷新分类树
          dispatch(fetchParentCategories()) // 刷新父级分类
        } else {
          message.error(result.payload || '新增失败')
        }
      } else {
        const result = await dispatch(editCategory({ 
          id: currentRecord.id, 
          data: values 
        }))
        if (result.type.includes('fulfilled')) {
          message.success('更新成功')
          setIsModalVisible(false)
          loadCategoryList()
          dispatch(fetchCategoryTree()) // 刷新分类树
        } else {
          message.error(result.payload || '更新失败')
        }
      }
    } catch (error) {
      // 表单验证失败，Ant Design会自动显示错误提示
    }
  }

  // 关闭对话框
  const handleCloseModal = () => {
    setIsModalVisible(false)
    form.resetFields()
    dispatch(resetCurrentCategory())
  }

  // 分页改变
  const handlePageChange = (page, size) => {
    loadCategoryList({ page, size })
  }

  // 父级分类改变时，自动设置层级
  const handleParentChange = (parentId) => {
    if (parentId === 0) {
      form.setFieldsValue({ level: 1 })
    } else {
      // 查找父级分类的层级
      const parent = parentCategories.find(p => p.id === parentId)
      if (parent) {
        form.setFieldsValue({ level: parent.level + 1 })
      }
    }
  }

  // 表格列配置
  const columns = [
    {
      title: '分类ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center'
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
      width: 150
    },
    {
      title: '父级分类',
      dataIndex: 'parentId',
      key: 'parentId',
      width: 120,
      render: (parentId) => {
        if (parentId === 0) {
          return <Tag color="purple">顶级分类</Tag>
        }
        const parent = parentCategories.find(p => p.id === parentId)
        return <Tag color="blue">{parent ? parent.name : `ID:${parentId}`}</Tag>
      }
    },
    {
      title: '层级',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      align: 'center',
      render: (level) => <Tag color={level === 1 ? 'gold' : 'cyan'}>L{level}</Tag>
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (time) => time ? new Date(time).toLocaleString('zh-CN') : '-'
    },
    {
      title: '状态',
      dataIndex: 'isEnabled',
      key: 'isEnabled',
      width: 100,
      render: (isEnabled, record) => (
        <Switch
          checked={isEnabled === 1}
          onChange={(checked) => handleStatusChange(record.id, checked)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            size="small" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.id, record.name)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  return (
    <div className="category-management-container">
      {/* 搜索表单 */}
      <Card className="search-card" title="查询表格">
        <div className="search-form">
          <div className="form-row">
            <div className="form-item">
              <label>分类名称</label>
              <Input
                placeholder="请输入分类名称"
                value={searchForm.name}
                onChange={(e) => setSearchForm({ ...searchForm, name: e.target.value })}
                onPressEnter={handleSearch}
              />
            </div>
            <div className="form-item">
              <label>状态</label>
              <Select
                placeholder="请选择状态"
                value={searchForm.isEnabled}
                onChange={(value) => setSearchForm({ ...searchForm, isEnabled: value })}
                style={{ width: '100%' }}
                allowClear
              >
                <Select.Option value={1}>启用</Select.Option>
                <Select.Option value={0}>禁用</Select.Option>
              </Select>
            </div>
            <div className="form-item">
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                查询
              </Button>
            </div>
            <div className="form-item">
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </div>
          </div>
        </div>
      </Card>

      {/* 操作按钮和表格 */}
      <Card className="table-card">
        <div className="table-toolbar">
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              新增分类
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={categoryList}
          loading={loading}
          rowKey="id"
          pagination={{
            total,
            current: currentPage,
            pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            onChange: handlePageChange
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新增/编辑对话框 */}
      <Modal
        title={modalType === 'add' ? '新增分类' : '编辑分类'}
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={handleCloseModal}
        width={600}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            name: '',
            parentId: 0,
            level: 1,
            sort: 0,
            isEnabled: 1,
            url: ''
          }}
        >
          <Form.Item
            label="分类名称"
            name="name"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            label="父级分类"
            name="parentId"
            rules={[{ required: true, message: '请选择父级分类' }]}
          >
            <Select 
              placeholder="请选择父级分类"
              onChange={handleParentChange}
            >
              <Select.Option value={0}>顶级分类</Select.Option>
              {parentCategories.map(cat => (
                <Select.Option key={cat.id} value={cat.id}>
                  {cat.name} (L{cat.level})
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="分类层级"
            name="level"
            rules={[{ required: true, message: '请输入分类层级' }]}
          >
            <InputNumber min={1} max={5} style={{ width: '100%' }} disabled />
          </Form.Item>

          <Form.Item
            label="排序序号"
            name="sort"
          >
            <InputNumber min={0} style={{ width: '100%' }} placeholder="数字越小越靠前" />
          </Form.Item>

          <Form.Item
            label="是否启用"
            name="isEnabled"
            valuePropName="checked"
            getValueFromEvent={(checked) => checked ? 1 : 0}
            getValueProps={(value) => ({ checked: value === 1 })}
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>

          <Form.Item
            label="分类链接URL"
            name="url"
          >
            <Input placeholder="请输入分类链接URL（可选）" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default CategoryManagement
